package com.config;


import com.config.log.BizConstants;
import com.config.log.LogFactory;
import com.controller.template.ResultCode;
import com.controller.template.ResultHelper;
import com.controller.template.ResultInfo;
import com.util.HttpUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ruiwen
 * @PROJECT_NAME: back_end
 */
@Aspect
@Configuration
@Order(3)
public class LogAspect {


    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* com.controller..*.*(..))")
    private void cutFilter() {

    }


    @Around("cutFilter()")
    public Object recardLog(ProceedingJoinPoint point) {
        //计时器
        StopWatch sw = new StopWatch();
        sw.start();
        //获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ResultInfo resultInfo = null;
        try {
            //记录请求日志
            LogFactory.printReqLog(request, AspectUtil.getParams(point));

            //执行目标方法
            Object proceed = point.proceed();

            resultInfo = ResultHelper.successResultInfo(proceed);
            //返回执行结果
            return proceed;
        } catch (Exception bizException) {
            /**
             * 自定义异常处理
             */
            LogFactory.printErrLog(bizException, request.getRequestURL().toString(), AspectUtil.getParams(point));
            resultInfo = ResultHelper.failResultInfo(300, bizException.getMessage());
            //钉钉消息警告
            String errorMsg = "警告：\n" +
                    "异常URL：" + request.getRequestURL().toString() + "\n" +
                    "请求参数：" + AspectUtil.getParams(point) + "\n" +
                    "请求 IP：" + HttpUtils.getIpAddress(request) + "\n" +
                    "错误信息：" + bizException.getMessage();
            logger.error(errorMsg);
        } catch (Throwable throwable) {
            resultInfo = ResultHelper.failResultInfo(ResultCode.FATAL_ERROR.getCode(), throwable.getMessage());
        } finally {
            sw.stop();
            String showResultInfo =
                    resultInfo != null ? resultInfo.isSuccess() + "," + resultInfo.getMessage() : "系统失败";
            logger.info(BizConstants.LOG_RESULT_FORMAT, request.getRequestURL().toString(), sw.getTime(), showResultInfo);
        }
        return resultInfo;
    }


}
